package com.bank.common;
 
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
 
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.util.UUID;
public class xmlGenerator {
 
	public static String createXML(List<List<String>> data) {
		UUID uid = UUID.fromString("38400000-8cf0-11bd-b23e-10b96e4ef00d");
		String FileName = uid.randomUUID().toString();
	  try {

		Iterator<List<String>> iterator = data.iterator();
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
 
		
		Document doc = docBuilder.newDocument();
		Element rootElement = doc.createElement("History");
		doc.appendChild(rootElement);
		
		int i = 0;
		while(iterator.hasNext()){
			String cc = iterator.next().toString();	
			String cc2 = cc.replace("[", "").replace("]", "");			
			String[] array = cc2.split(",",-1);
			
			Element trans = doc.createElement("Transaction");
			rootElement.appendChild(trans);
			trans.setAttribute("Nr", String.valueOf(i));
			
			Element id = doc.createElement("Transaction_id");
			id.appendChild(doc.createTextNode(array[1]));
			trans.appendChild(id);
			
			Element kn = doc.createElement("Pay_Account");
			kn.appendChild(doc.createTextNode(array[4]));
			trans.appendChild(kn);
			
			Element ku = doc.createElement("Reciever_account");
			ku.appendChild(doc.createTextNode(array[5]));
			trans.appendChild(ku);
			
			Element apj = doc.createElement("Amount");
			apj.appendChild(doc.createTextNode(array[7]));
			trans.appendChild(apj);
			
			Element dt = doc.createElement("Transaction_time");
			dt.appendChild(doc.createTextNode(array[8]));
			trans.appendChild(dt);
			
			Element apr = doc.createElement("Details");
			apr.appendChild(doc.createTextNode(array[6]));
			trans.appendChild(apr);
			i++;
		}
		// write the content into xml file
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(new File("src\\main\\webapp\\resources\\xml\\xmlHistory-"+FileName+".xml"));
		transformer.transform(source, result);
		System.out.println("File saved!");
	  } catch (ParserConfigurationException pce) {
		pce.printStackTrace();
	  } catch (TransformerException tfe) {
		tfe.printStackTrace();
	  }
	  return "xmlHistory-"+FileName+".xml";
	}
	
}